<?php
namespace App\Admin\Controllers\OverSeasIn;

use App\Admin\Actions\OverSeasIn\ImportOSRemovaleOrderDetail;
use App\Admin\Actions\OverSeasIn\RemovaleOrderDetailCheck;
use App\Admin\Actions\OverSeasIn\RemovaleOrderDetailStock;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysArea;
use App\Models\OverSeasBa\Warehouse;
use App\Models\OverSeasIn\RemovaleOrderDetail;
use App\Models\Product\ProductClassify;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Request;

class RemovaleDetailController extends AdminController{

    protected $title = 'FBA移库明细(移库至海外仓)';

    protected function grid()
    {
        $grid = new Grid(new RemovaleOrderDetail());

        $grid->model()->orderBy('id', 'DESC');
        $grid->column('account_id','账号')->display(function ($value){
            return SysPlatAccount::getAccountById($value);
        });
        $grid->column('order_id','订单');
        $grid->column('seller_sku','平台SKU');
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('sku.classify_id','品类')->display(function ($value){
            if($value){
                return ProductClassify::getTitleById($value);
            }
            return '';
        });
        $grid->column('fnsku','FNSKU');
        $grid->column('warehouse.w_code','仓库');
        $grid->column('area.area','站点');
        $grid->column('country.country','国家');
        $grid->column('requested_quantity','请求')->totalRow();
        $grid->column('cancelled_quantity','取消')->totalRow();
        $grid->column('disposed_quantity','Disposed')->totalRow();
        $grid->column('shipped_quantity','发运')->totalRow();
        $grid->column('in_process_quantity','处理中')->totalRow();
        $grid->column('ship_quantity','已入库')->totalRow();
        $grid->column('this_quantity_tmp','本次入库')->totalRow()->display(function ($value, $column){
            if($this->status == 1 && Admin::user()->can('os-in.os.removale-detail-upload')){
                return $column->editable();
            }
            return $value;
        });
        $grid->column('status','状态')->display(function ($value){
            return RemovaleOrderDetail::$_status[$value];
        });
        $grid->column('created_at','创建时间');

        $grid->fixColumns(0,0);
        $grid->disableActions();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            if(Admin::user()->can('os-in.os.removale-detail-upload')){
                $tools->append(new ImportOSRemovaleOrderDetail());
            }
            $tools->append(new Export('overseas-in/removale-detail-download'));
        });
        $grid->disableCreateButton();
        $grid->fixHeader();
        if(!Admin::user()->can('os-in.os.removale-detail-upload')){
            $grid->disableRowSelector();
        }else{
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                $batch->disableDelete();
                $batch->add(new RemovaleOrderDetailStock()); //入库
                $batch->add(new RemovaleOrderDetailCheck()); //完结
            });
        }
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('order_id','订单');
                $filter->equal('account_id','账号')->select(SysPlatAccount::options());
                $filter->equal('area_id', '站点')->select(SysArea::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('fnsku','FNSKU');
                $filter->equal('seller_sku','平台SKU');
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
                $filter->between('created_at', '创建时间')->datetime();
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('status', '状态')->select(RemovaleOrderDetail::$_status);
                $filter->equal('warehouse_id', '仓库')->select(Warehouse::options());
                $filter->equal('country_id', '国家')->select(AmazonCountry::options());
            });
        });
        return $grid;
    }

    protected function form()
    {
        $form = new Form(new RemovaleOrderDetail());
        $form->text('this_quantity_tmp');
        return $form;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = RemovaleOrderDetail::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if(in_array($key,['order_id','account_id','fnsku','warehouse_id','area_id','country_id','status','seller_sku'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['账号','订单','平台SKU','FNSKU','SKU','产品名称','品类','仓库','站点','国家','请求数量','取消数量',
            'Disposed数量','发运数量','处理中数量','实际数量','状态','时间'];
        RExcel::exportCsv('移库明细',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $account = [];
        $warehouse = [];
        $title = [];
        foreach ($res as $model){
            $accountId = $model->account_id ?: -1;
            if(!array_key_exists($accountId,$account)){
                $account[$accountId] = SysPlatAccount::getAccountById($accountId);
            }
            $warehouseId = $model->warehouse_id ?: -1;
            if(!array_key_exists($warehouseId,$warehouse)){
                $warehouse[$warehouseId] = Warehouse::getCodeById($warehouseId);
            }
            $classifyId = $model->sku->classify_id ?? -1;
            if(!array_key_exists($classifyId,$title)){
                $title[$classifyId] = ProductClassify::getTitleById($classifyId);
            }
            $temp = [
                $account[$accountId],
                $model->order_id,
                $model->seller_sku,
                $model->fnsku,
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                $title[$classifyId],
                $warehouse[$warehouseId],
                $model->area->area ?? '',
                $model->country->country ?? '',
                $model->requested_quantity,
                $model->cancelled_quantity,
                $model->disposed_quantity,
                $model->shipped_quantity,
                $model->in_process_quantity,
                $model->ship_quantity,
                RemovaleOrderDetail::$_status[$model->status],
                $model->created_at ?? '',
            ];
            yield $temp;
        }
    }
}
